<template xmlns="http://www.w3.org/1999/html">
  <div style="margin-left: 20px;margin-top: 20px">
    <div class="container">
      <el-input v-model="input" class="input-field" style="width: 300px" placeholder="请输入关键词" />
      <el-select v-model="selectvalue" placeholder="请选择" style="margin-right: 10px;">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <br>
      <el-button class="input-field" type="primary" icon="el-icon-search" @click="ck">查询</el-button>
      <el-button type="warning" icon="el-icon-circle-plus" @click="showFormxz">新增</el-button>

    </div>
    <br>
    <el-table v-loading="loading" :data="displayedData" style="">
      <el-table-column v-if="showColumnid" prop="healthid" label="编号" />
      <el-table-column prop="codes" label="编码" />
      <el-table-column prop="healthname" label="方案标题" />
      <el-table-column prop="keyword" label="关键词" />
      <el-table-column prop="schemename" label="方案类型" />
      <el-table-column prop="content" label="内容" />
      <el-table-column prop="remarks" label="备注" />
      <el-table-column prop="status" label="状态">
        <template v-slot="scope">
          {{ scope.row.status === 0 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="操作">
        <!-- 使用v-for循环渲染按钮 -->
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" @click="showEditForm(scope.row.healthid)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="open(scope.row.healthid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>

    <el-pagination
      style="float: right"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog title="新增" :visible.sync="showForm">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="方案标题" prop="healthname">
          <el-input v-model="ruleForm.healthname" />
        </el-form-item>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="ruleForm.keyword" />
        </el-form-item>
        <el-form-item label="方案类别" prop="schemename">
          <el-select v-model="ruleForm.schemename" placeholder="活动区域">
            <el-option label="心理干预" value="心理干预" />
            <el-option label="戒烟限酒" value="戒烟限酒" />
            <el-option label="注意事项" value="注意事项" />
            <el-option label="运动干预" value="运动干预" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="ruleForm.content" type="textarea" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="ruleForm.remarks" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="showFormxg">
      <el-form ref="rulexgForm" :model="rulexgForm" :rules="rules2" label-width="100px">
        <el-form-item label="编号" prop="healthid">
          <el-input v-model="rulexgForm.healthid" readonly />
        </el-form-item>
        <el-form-item label="编码" prop="codes">
          <el-input v-model="rulexgForm.codes" readonly />
        </el-form-item>
        <el-form-item label="方案标题" prop="healthname">
          <el-input v-model="rulexgForm.healthname" />
        </el-form-item>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="rulexgForm.keyword" />
        </el-form-item>
        <el-form-item label="方案类别" prop="schemename">
          <el-select v-model="rulexgForm.schemename" placeholder="活动区域">
            <el-option label="心理干预" value="心理干预" />
            <el-option label="戒烟限酒" value="戒烟限酒" />
            <el-option label="注意事项" value="注意事项" />
            <el-option label="运动干预" value="运动干预" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="rulexgForm.content" type="textarea" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="rulexgForm.remarks" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="rulexgForm.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormxg('rulexgForm')">确定</el-button>
          <el-button @click="resetFormxg('rulexgForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>
<style>

.container {
  display: flex;
  align-items: center;
}

.input-field {
  margin-right: 10px; /* 调整元素之间的间距 */

}

</style>
<script>
import row from 'element-ui/packages/row'
import axios from 'axios'
import getters from '@/store/getters'
export default {
  data() {
    return {
      options: [{
        value: '',
        label: ''
      }, {
        value: '心理干预',
        label: '心理干预'
      }, {
        value: '戒烟限酒',
        label: '戒烟限酒'
      }, {
        value: '饮食干预',
        label: '饮食干预'
      }, {
        value: '注意事项',
        label: '注意事项'
      }, {
        value: '运动干预',
        label: '运动干预'
      }],
      selectvalue: '',

      message: '', // 返回结果成功没
      article: '',
      loading: true,
      input: '',
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      activeName: 'first',
      showFormxg: false, // 控制修改表单的显示
      showForm: false, // 控制添加表单的显示状态，默认隐藏
      showColumnid: false, // 控制id数据的隐藏
      showbz: false, // 控制备注数据隐藏
      displayedData: [], // 分页后的

      rulexgForm: {
        status: '',
        codes: '',
        healthid: '',
        healthname: '',
        keyword: '',
        schemename: '',
        content: '',
        remarks: ''
      },
      ruleForm: {
        healthname: '',
        keyword: '',
        schemename: '',
        content: '',
        remarks: ''
      },
      rules: {
        healthname: [
          { required: true, message: '请输入方案标题', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ],
        schemename: [
          { required: true, message: '请选中方案类型', trigger: 'select' }
        ],
        content: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请填写备注', trigger: 'blur' }
        ]
      },
      rules2: {
        healthname: [
          { required: true, message: '请输入方案标题', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ],
        schemename: [
          { required: true, message: '请选中方案类型', trigger: 'select' }
        ],
        content: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请填写备注', trigger: 'blur' }
        ],
        STATUS: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }

    }
  },
  computed: {
    row() {
      return row
    }
  },
  mounted() {
    // 最初调用loadData()方法以填充表格
    const est = {}
    est.name = this.input
    this.fetchArticle(est)
  },
  methods: {
    open(id) {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'deletepgjy') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击 "确定" 按钮时执行删除操作
          this.deleteItem(id) // 传递 id 参数
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    deleteItem(id) {
      this.deletees(id)
      // 在这里执行删除操作，使用传递的 id 参数
      // 可以调用你的删除方法，传递 id 参数
      // 例如：this.$axios.delete(`/api/items/${id}`)
      // 然后处理成功和失败的情况
      // 成功：显示删除成功的消息
      // 失败：显示删除失败的消息
    },
    // 当每页显示条数发生变化时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      // 根据新的每页显示条数重新加载数据
      this.loadData()
    },

    // 当前页码发生变化时触发
    handleCurrentChange(val) {
      this.currentPage = val
      // 根据新的当前页码重新加载数据
      this.loadData()
    },
    // 根据当前页和每页显示的数量加载数据
    loadData() {
      console.log(this.article)
      const startIndex = (this.currentPage - 1) * this.pageSize// 得到当前页从哪一页显示的
      const endIndex = startIndex + this.pageSize// 得到下一页的页
      this.displayedData = this.article.slice(startIndex, endIndex)// （5，10）显示的是第二页的
      this.loading = false
    },
    // 确定添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')

          // 在验证通过后获取表单数据
          const formData = { ...this.ruleForm }
          console.log(formData)

          // 执行其他操作，例如发送表单数据到后端
          this.addes(formData)
          this.$refs[formName].resetFields()
          this.showForm = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 确定修改
    submitFormxg(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
          const formData = { ...this.rulexgForm }
          this.updatees(formData)
          this.$refs[formName].resetFields()
          this.showFormxg = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 显示添加页面
    showFormxz() {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'addjkfa') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        this.showForm = true
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    // 显示修改页面
    showEditForm(id) {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'updatepgjy') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        const data = this.displayedData.find((user) => user.healthid === id)
        this.showFormxg = true
        // 给修改页面赋值
        this.rulexgForm.healthid = data.healthid
        this.rulexgForm.healthname = data.healthname
        this.rulexgForm.keyword = data.keyword
        this.rulexgForm.schemename = data.schemename
        this.rulexgForm.content = data.content
        this.rulexgForm.remarks = data.remarks
        this.rulexgForm.codes = data.codes
        this.rulexgForm.status = data.status.toString()
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    // 添加页面取消
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.showForm = false
    },
    // 修改页面取消
    resetFormxg(formName) {
      this.$refs[formName].resetFields()
      this.showFormxg = false
    },
    // 查询名称方法
    ck() {
      const est = {}
      est.name = this.input
      est.typename = this.selectvalue
      this.fetchArticle(est)
    },
    // 查询方法
    async fetchArticle(est) {
      console.log(est)
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/HealthPlan/queryHealthPlan', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        // eslint-disable-next-line no-unused-vars
        const { code, flag, message, data } = response.data
        this.article = data
        this.message = message
        this.totalItems = this.article.length
        this.loadData()
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async addes(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/HealthPlan/addhp', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async updatees(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/HealthPlan/updatehp', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async deletees(id) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post(`/api/HealthPlan/deletehp/${id}`, null, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        console.log(this.article)
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    }
  }

}

</script>
